<?php

namespace app\librarys;

use app\models\Manager;
use app\models\ManagerExceptionLog;
use app\models\ManagerOperateLog;
use app\models\Permission;
use yii\web\Controller;

class BaseController extends Controller
{
    public $enableCsrfValidation = false;

    public function beforeAction($action)
    {
        $isRecordLog = \Yii::$app->params['isRecordLog'];
        if ($isRecordLog == true) {
            // 记录请求日志
            $logId = ManagerOperateLog::add(
                $action->controller->id,
                $action->id,
                $_GET,
                $_POST,
                Manager::getCurrentManager()['id'],
                Manager::getCurrentManager()['name'],
                $_SERVER['REMOTE_ADDR'],
                $_SERVER['HTTP_USER_AGENT'],
                $_SERVER['REQUEST_TIME']
            );
            \Yii::$app->session->set('request_manager_operate_log_id', $logId);
            \Yii::$app->session->set('request_manager_timestamp', Tools::getMillisecond());
        }


        $currentManager = Manager::getCurrentManager();
        if ($currentManager == null) {
            return $this->redirect(['site/login', 'redirect_url' => \Yii::$app->request->url])->send();
        }
        $hasPermission = Permission::hasPermission($action->controller->id, $action->id);
//        $hasPermission = true;
        if ($hasPermission) {
            return parent::beforeAction($action); // TODO: Change the autogenerated stub
        } else {
            throw new \Exception('无此权限,请重新登录!');
        }
    }

    function runAction($id, $params = [])
    {
        try {
            return parent::runAction($id, $params);
        } catch (\Exception $ex) {
            $isRecordLog = \Yii::$app->params['isRecordLog'];
            if ($isRecordLog == true) {
                // 记录异常日志
                $logId = \Yii::$app->session->get('request_manager_operate_log_id');
                if ($logId != null) {
                    ManagerOperateLog::setException($logId, $ex);

                    $operateLog = ManagerOperateLog::getById($logId);
                    if ($operateLog != null) {
                        ManagerExceptionLog::add(
                            $operateLog->controllerId,
                            $operateLog->actionId,
                            $operateLog->getParams,
                            $operateLog->postParams,
                            $operateLog->managerId,
                            $operateLog->managerName,
                            $operateLog->remoteAddr,
                            $operateLog->httpUserAgent,
                            $operateLog->createDatetime,
                            $ex
                        );
                    }
                }
            }
            throw $ex;
        }
    }

    public function afterAction($action, $result)
    {
        $isRecordLog = \Yii::$app->params['isRecordLog'];
        if ($isRecordLog == true) {
            // 记录请求总共耗时(毫秒)
            $logId = \Yii::$app->session->get('request_manager_operate_log_id');
            if ($logId != null) {
                $time = Tools::getMillisecond();
                $time = $time - \Yii::$app->session->get('request_manager_timestamp');
                ManagerOperateLog::setDurationTime($logId, $time);
            }
        }

        return parent::afterAction($action, $result);
    }


    /**
     * @param $data array|mixed
     * @param $status int   0:success
     * @param $message string
     * @return string
     */
    public function renderJson($data = null, $status = 0, $message = 'success')
    {
        $result = [
            'status' => $status,
            'message' => $message,
            'data' => $data
        ];

        return json_encode($result, true);
    }
}